#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "progress_bar.h"
#include "debug.h"

static struct progress_bar progress_bar_data = {
	.sign = SETTING_SIGN,
	.length = SETTING_LENGTH,
	.speed = SETTING_SPEED,
	.color = SETTING_COLOR,
};


int progress_bar_init(void)
{
	if (progress_bar_data.length < LENGTH_MIN || progress_bar_data.length > LENGTH_MAX) {
		DEBUG(BAR_RED"ERROR:setting wrong length!\n"BAR_TAIL);
		return FAIL;
	}

	if (progress_bar_data.speed < SPEED_MIN || progress_bar_data.speed > SPEED_MAX) {
		DEBUG(BAR_RED"ERROR:setting wrong speed!\n"BAR_TAIL);
		return FAIL;
	}

	if (progress_bar_data.color < COLOR_MIN || progress_bar_data.color > COLOR_MAX) {
		DEBUG(BAR_RED"ERROR:setting wrong color!\n"BAR_TAIL);
		return FAIL;
	}

	return SUCCESS;
}

int progress_bar_run(void)
{
	char progress_bar[progress_bar_data.length];
	const char* lable = "-\\|/";
	int rate = 0;
	int sign_position = 0;

	memset(progress_bar, ' ', sizeof(progress_bar)+4);

	while (rate <= 100) {

		switch(progress_bar_data.color) {
			case NOMAL:
				printf("[ %s] [%d%%] %c\r", progress_bar, rate, lable[rate%4]);
				break;
			case RED:
				printf(BAR_RED"[ %s] [%d%%] %c\r"BAR_TAIL, progress_bar, rate, lable[rate%4]);
				break;
			case GREEN:
				printf(BAR_GREEN"[ %s] [%d%%] %c\r"BAR_TAIL, progress_bar, rate, lable[rate%4]);
				break;
			case YELLOW:
				printf(BAR_YELLOW"[ %s] [%d%%] %c\r"BAR_TAIL, progress_bar, rate, lable[rate%4]);
				break;
			case BLUE:
				printf(BAR_BLUE"[ %s] [%d%%] %c\r"BAR_TAIL, progress_bar, rate, lable[rate%4]);
			default:
				break;
		}
		sign_position = ((float)progress_bar_data.length / 100) * rate;
		progress_bar[sign_position] = progress_bar_data.sign;
		fflush(stdout);
		rate++;
		usleep(progress_bar_data.speed * progress_bar_data.speed * 1000 + 500);
	}
	printf("\n");

	return SUCCESS;
}

void progress_bar_reset(void)
{
	printf(BAR_BLUE"PROGRESS_BAR ENDING!\n"BAR_TAIL);

	progress_bar_data.sign = SETTING_SIGN;
	progress_bar_data.length = SETTING_LENGTH;
	progress_bar_data.speed = SETTING_SPEED;
	progress_bar_data.color = SETTING_COLOR;

}
